// index.js
const app = getApp()

Page({
  data: {
    categories: [],
    recentRecipes: [],
    loading: true,
    cloudError: false
  },

  onLoad: function() {
    // 直接初始化本地数据
    this.initLocalData();
  },

  onShow: function() {
    // 每次页面显示时都重新加载数据
    this.initLocalData();
  },

  // 初始化本地数据
  initLocalData: function() {
    console.log('使用本地分类数据');
    this.setData({ loading: true });
    
    // 格式化本地数据，保持字段名一致，并计算每个分类下的配方数量
    const localCategories = app.globalData.categories.map(item => {
      // 计算该分类下的配方数量
      const recipeCount = app.globalData.recipes.filter(
        recipe => recipe.categoryId === item.id.toString()
      ).length;
      
      return {
        _id: item.id.toString(),
        id: item.id,
        name: item.name,
        icon: item.icon,
        recipeCount: recipeCount
      };
    });
    
    // 设置本地数据
    this.setData({
      categories: localCategories,
      recentRecipes: app.globalData.recipes.slice(-5), // 只显示最近5个配方
      loading: false,
      cloudError: false
    });
  },

  // 点击重试按钮
  retryLoading: function() {
    this.initLocalData();
  },

  // 跳转到配方列表页
  goToRecipeList(e) {
    const { id, name } = e.currentTarget.dataset;
    if (!id) {
      wx.showToast({
        title: '无效的分类',
        icon: 'none'
      });
      return;
    }
    
    wx.navigateTo({
      url: `/pages/recipeList/recipeList?categoryId=${id}&categoryName=${name}`
    });
  },

  // 跳转到配方详情页
  goToRecipeDetail(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/recipeDetail/recipeDetail?id=${id}`
    });
  },

  // 跳转到分类管理页
  goToCategoryManage() {
    wx.navigateTo({
      url: '/pages/categoryManage/categoryManage'
    });
  },

  // 跳转到新建配方页
  createNewRecipe() {
    wx.navigateTo({
      url: '/pages/recipeEdit/recipeEdit'
    });
  }
});
